const express = require('express')
const fs = require('fs')
const path = require('path')
const routers = express.Router()

const resolve = (...args) => path.resolve(__dirname, ...args)
const listJSONPath = resolve('../data/list.json')

function getList() {
  return new Promise((resolve) => {
    fs.readFile(listJSONPath, { encoding: 'utf-8' }, (err, data) => {
      if (err) return resolve([])
      resolve(JSON.parse(data))
    })
  })
}

function modifyList(data) {
  return new Promise((resolve) => {
    fs.writeFile(listJSONPath, JSON.stringify(data, null, 2), (err) => {
      if (err) return resolve({ code: 400, message: 'faild' })
      resolve({ code: 200, message: 'success' })
    })
  })
}

/** 获取列表 */
routers.get('/users', async (req, res) => {
  let list = await getList()
  list.sort((a, b) => b.time - a.time)
  res.send({ code: 200, data: list })
})

/** 添加list */
routers.post('/add', async (req, res) => {
  let data = await getList()

  let params = Object.assign(req.body, {
    id: data.length ? data[data.length - 1].id + 1 : 1,
    time: Date.now()
  })

  data.push(params)
  let result = await modifyList(data)
  res.statusCode = 201
  res.send({ ...result, code: 201, data: params })
})

/** 删除list */
routers.delete('/del/:id', async (req, res) => {
  let data = await getList()
  data = data.filter((item) => item.id !== +req.params.id)

  let result = await modifyList(data)
  res.statusCode = 204
  res.send({ ...result, code: 204, message: 'success' })
})

/** 更新User */
routers.put('/put', async (req, res) => {
  let data = await getList()
  let i = data.findIndex((item) => item.id === +req.body.id)
  data[i] = Object.assign(data[i], req.body)

  let result = await modifyList(data)
  res.send(result)
})

/** 查找单个数据 */
routers.get('/users/:id', async (req, res) => {
  let data = await getList()
  data = data.find((item) => item.id === +req.params.id)
  if (!data) {
    res.send({ code: 400, message: '没有该id' })
  }
  res.send({ code: 200, message: 'success', data })
})

module.exports = routers
